# -*- coding: utf-8 -*-
'''
    :file: auth.py
    :author: -Farmer
    :url: https://blog.farmer233.top
    :date: 2021/02/14 16:07:26
'''
from operator import add
import re
import os
import shutil
import random
from flask import current_app
# from flask.app import Flask
# from itsdangerous import BadSignature
from app.extensions import db
from app.models import User
from app.utils import TokenTimeout, generate_token, validate_token
from app.mails import send_forget_password_code_mail
from itsdangerous import BadSignature, SignatureExpired, TimedJSONWebSignatureSerializer as Serializer

# 注册用户表单
class RegisterForm(User):
    def __init__(self, address) -> None:
        self.address = address
    
    # 设置用户名
    def set_username(self, username: str):
        user_exit = User.query.filter(User.username == username).count()
        if user_exit:
            raise ValueError("用户已存在")

        rule = '[A-Za-z][A-Za-z0-9_]*'
        if not(4 <= len(username) <= 12):
            raise ValueError("用户名长度不合法")

        rule_status = re.findall(rule, username)
        if rule_status[0] != username:
            raise ValueError("用户名不合法")
        else:
            self.username = username
            user_path = os.path.join(current_app.config['UPLOAD_FOLDER'], username)
            if os.path.exists(user_path):
                shutil.rmtree(user_path)
            os.mkdir(user_path)
    
    # 设置用户邮箱
    def set_email(self, email:str):
        email = email.lower()
        rule = "[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?"
        match = re.match(rule, email)
        if not match:
            raise ValueError('邮箱不合法')
        self.email = email
    
    # 设置管理员信息
    def set_admin(self, username, password, email, power=1):
        self.set_email(email=email)
        self.set_username(username)
        self.set_password(password=password)
        self.power = power

# 重置密码表单
class RestPasswordForm(User):
    def __init__(self, username) -> None:
        super().__init__()
        self.username = username
        user = User.query.filter(User.username == username).first()
        if user is None:
            raise ValueError("用户不存在，请先注册")
        else:
            self.user = user

    def send_mail_code(self):
        ''' 
            1. 生成验证码
            2. 将验证码邮件发送
            3. 生成带验证码的token令牌并返回给前端
        '''
        code = str(random.randint(999, 10000))
        token = generate_token(code=code, user=self.user)
        send_forget_password_code_mail(user=self.user, code=code)
        return token
    
    def check_code(self, token="", code:str=-1):
        '''
            验证用户输入的验证码和token中的验证码
            一致则返回用户对象
        '''
        try:
            datas = validate_token(token=token)
            token_user = User.query.get(datas['id'])
            if token_user.username != self.username:
                raise ValueError("用户不正确")

            if code != datas["code"]:
                raise ValueError("验证码错误")
            return token_user
        except TokenTimeout as e:
            raise ValueError(e)
        except BadSignature as e:
            raise ValueError(e)
        except Exception as e:
            print(type(e))

    # 重新设置密码
    def rest_password(self, token, code, new_password):
        ''' 
            通过check_code函数，判断是否验证成功
        '''
        status = self.check_code(token=token, code=code, username=self.username)
        if status:
            self.user.set_password(password=new_password)
            db.session.commit()

# 管理员登录表单
class AdminLoginForm(User):
    def __init__(self) -> None:
        super().__init__()
    
    def login(self):
        admin = User.query

    # 生成管理员特有的令牌（token）
    def generate_admin_token(self, expiration=3600 * 24 * 7):
        s = Serializer(current_app.config["SECRET_KEY"], expires_in=expiration)
        return s.dumps({
            'id': self.id,
            'username': './',
            'power': self.power
        }).decode()
